import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:xindong/common/xindong_methods.dart';
import 'package:xindong/utils/xindong_cache_util.dart';
import 'package:xindong/utils/xindong_text_util.dart';
import 'package:xindong/utils/queue/xindong_svga_queue.dart';
import 'package:xindong/widgets/animation/xindong_animation_gift.dart';

/*
XinDongGiftAnimationOverlay.instance.addQueue(SVGAClass(
      type: SVGAType.receiveGift,
      name: "鲜花",
      svga: "http://paopao.cn-gd.ufileos.com/gift/aidejuanzhou/svga.svga",
      owner: XinDongAccountUser.mineUserClass,
      target: XinDongAccountUser.mineUserClass,
    ));
    */

// 礼物动画悬浮
// 要添加到全局providers ChangeNotifierProvider(create: (context) => XinDongGiftAnimationOverlay.instance),
class XinDongGiftAnimationCtr extends GetxController {
  static XinDongGiftAnimationCtr get to => Get.find();

  @override
  void onInit() {
    super.onInit();
    init();
  }

  // 悬浮层
  OverlayEntry? overlayEntry;

  // 自定义
  late XinDongSVGAQueue queue; // 队列
  late Widget showWidget = const SizedBox(); // 给外部显示的视图

  // 添加到队列
  // 必须有svga属性
  void addQueue(SVGAClass object) async {
    if (TextUtil.isEmpty(object.svga)) {
      return;
    }
    queue.addQueue(object);
    show();
  }

  // 清除
  void clear() {
    queue.clear();
    hide();
  }

  // 初始化动画队列
  void init() {
    queue = XinDongSVGAQueue(
      fit: BoxFit.cover,
      onStart: (model, animationSVGA) {
        showWidget = XinDongAnimationReceiveGift(model: model, animationSVGA: animationSVGA);
        update();
      },
      onEnd: () {
        showWidget = const SizedBox();
        update();
        hide();
      },
    );
  }

  // 创建并显示
  void show() {
    BuildContext? context = navigatorKey.currentContext;
    if (context == null) {
      return;
    }
    final overlay = Overlay.of(context);
    // 避免重复添加
    if (overlayEntry == null) {
      overlayEntry = OverlayEntry(
        opaque: false,
        maintainState: false,
        builder: (BuildContext context) {
          return GetBuilder<XinDongGiftAnimationCtr>(builder: (provider) {
            return provider.showWidget;
          });
        },
      );
      overlay.insert(overlayEntry!);
    }
  }

  // 隐藏并销毁
  void hide() {
    overlayEntry?.remove();
    overlayEntry = null;
  }
}
